<template>
  <div>
    <div class="imgUpload">
      <input ref="imgChecked" type="file" accept="image/*" multiple="multiple" capture="camera" style="display: none">
      <span>
        <a href="javascript:;" @click="clickToUpload">点击上传</a>
      </span>
    </div>
    <img :src="qyyyzz">
  </div>
</template>
<script>
import { upload } from '@/api/article';
import checkFileType from '@/utils/checkFileType';
import getBase64Image from '@/utils/utils';
import { Toast } from 'vant';

export default {
  data() {
    return {
      qyyyzz: '' // 营业执照
    };
  },
  methods: {
    clickToUpload() {
      var ele = this.$refs['imgChecked'];
      ele.onchange = () => {
        var file = ele.files[0] || '';
        console.log(file);
        if (file) {
          // 检验文件类型
          var bool = checkFileType(file.name, ['png', 'jpg', 'jpeg']);
          if (!bool) {
            ele.value = '';
            Toast('文件类型错误');
            return;
          }
          var img = new Image();
          img.onload = () => {
            var base64 = getBase64Image(img);
            this.qyyyzz = base64;
            var data = {
              requestSn: '111111',
              image: base64
            };
            console.log('input---->' + JSON.stringify(data));
            upload(data)
              .then(response => {
                console.log(response);
                // 赋值
              })
              .catch(err => {
                console.log('error:' + JSON.stringify(err));
              });
            ele.value = '';
          };
          img.src = window.URL.createObjectURL(file);
        }
      };
      ele.dispatchEvent(new MouseEvent('click'));
      // ele.click()
    }
  }
};
</script>

<style scoped>
.imgUpload {
  width: 100%;
}
.imgUpload a {
  width: 80%;
  margin-left: 10%;
  background: #fff;
  margin-top: 1rem;
  margin-bottom: 1rem;
  text-align: center;
  float: left;
  border-radius: 10px;
  position: relative;
}
.topimg {
  width: 2rem;
}
img {
  margin-left: 20%;
  max-width: 60%;
}
</style>
